import store from '@/store'
import {
	baseURL
} from './config'

const statusMap = {
	401: "无权限调用此服务！",
	404: "找不到对应的地址！",
	500: "服务器处理出错！",
	504: "服务器返回超时！"
};
const errorCodeMap = {
	"-99": "您的账号在其他地方已登录，请重新登录！",
	"-100": "身份认证过期或错误，请重新登录！",
	"-98": "身份认证过期，请重新登录！",
	"-101": "长时间未操作，请重新登录！"
};

function errorHandler(res) {
	// 请求拦截
	if (res.statusCode === 200) {
		let data = res.data;
		//有错误编码，编码小于0，或者编码大于1000000 并且小于 9900000时表示是有错误的信息，需要提示
		if (data.code && (data.code < -1 || (data.code >= 1000000 && data.code < 9900000))) {
			let content = errorCodeMap[data.code] || "错误编码：" + data.code + "，错误信息：" + data.message;
			if (data.code == '-98') {
				store.commit('logout')
				uni.showModal({
					title: '提示',
					content: '您尚未登录，是否登录？',
					cancelText: "继续逛逛",
					confirmText: "登录",
					success: function(res) {
						if (res.confirm) {
							// console.log('用户点击确定');
							uni.navigateTo({
								url: `/pages/public/login`
							})
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				});
				return false
			}

			if (errorCodeMap[data.code]) {
				store.commit('logout')
				uni.showModal({
					title: '提示',
					content: content,
					showCancel:false,
					confirmText: "去登录",
					success: function(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: `/pages/public/login`
							})
						}
					}
				});
				// uni.showToast({
				// 	 title: content,
				// 	 duration: 3000,
				// 	 mask:false,
				// 	 icon:'none'
				// });
				// setTimeout(()=>{
				// 	uni.navigateTo({
				// 		url: `/pages/public/login`
				// 	})
				// }, 1200);
			}
			return false;
		} else if (data.code == -1) {
			if(data.message != '购物车装不下啦，请清理后再试！'){
				uni.showToast({
					title: data.message,
					duration: 3000,
					mask: false,
					icon: 'none'
				});
			}
		}
		return true;
	} else {
		uni.showToast({
			title: `status:${res.status},${statusMap[res.status] || "网络错误，请重试"}${res.data.message}`,
			duration: 3000,
			mask: false,
			icon: 'none'
		});
		return false;
	}
}

// 获取请求方式
function getConfig(opts) {

	let defaultHeader = Object.assign({}, store.state.header, opts.header || {});
	if(!defaultHeader||!defaultHeader.Authorization){
		const defaultToken = uni.getStorageSync('token')
		if(defaultToken)
			defaultHeader = {
				"Authorization": "Bearer " + defaultToken
			}
	}
	// console.log('defaultHeader',defaultHeader)
	// let defaultHeader = Object.assign({}, uni.getStorageSync('header'), opts.header || {});

	let config = Object.assign({
		method: 'GET',
		data: {}
	}, opts, {
		header: defaultHeader
	});
	let {
		method,
		data
	} = config;
	if (method && (method.toUpperCase() === 'GET')) {
		config.data = {
			t: Date.parse(new Date()) / 1000,
			...data
		};
	}
	return config;
}


function Request(url, opts) {
	let config = getConfig(opts);
	let reqUrl = baseURL + url;
	// settings接口不需要header token
	if(url.includes('/api/mobile/settings')){
		config['header'] = {}
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: reqUrl,
			...config,
			success: res => {
				if (errorHandler(res)) {
					resolve(res.data);
				} else {
					reject(res);
				}
			},
			fail: err => {
				reject(err)
			}
		})
	}).catch(err => {
		console.log('err',err)
		console.log( err.errMsg)
		uni.showToast({
			title: err.errMsg,
			duration: 2000,
			mask: false,
			icon: 'none'
		});
	})
}


export default Request;
